import React, { lazy } from 'react'
import dictionary from './dictionary'

type IRoutes = IRouter.Config.Route[]

const Default = lazy(() => import('@/layout/default'))
const Error404 = lazy(() => import('@/pages/Error/404'))
const Error401 = lazy(() => import('@/pages/Error/401'))
const Login = lazy(() => import('@/pages/Login'))

const baseRoutes: IRoutes = [
  {
    label: 'root',
    key: 'root',
    path: '/',
    element: <Default />
  },
  {
    label: 'login',
    key: '登录',
    path: '/login',
    element: <Login />
  },
  {
    label: '没有权限',
    key: 'error.unAccess',
    path: '/401',
    element: <Error401 />
  },
  {
    label: '页面找不到',
    key: 'error.notFound',
    path: '*',
    element: <Error404 />
  }
]

export function accessRouterHelper(
  dict: IRouter.Config.Route[],
  access: string[]
): IRouter.Config.Route[] {
  return dict.map((v) => {
    const children = v.children ? accessRouterHelper(v.children, access) : undefined
    const origin = { ...v, children }
    const accessExtra = { ...v, access: access.includes(v.key), children }
    // 用于菜单过滤
    return !access.includes(v.key) ? accessExtra : origin
  })
}

export function getRouteByAccess(access: IUser.Response.IAccess[]): IRouter.Config.Route[] {
  const accessCodes = access.map((v) => v.key)
  return accessRouterHelper(dictionary, accessCodes)
}

export function getEvaluatedRoutes(access?: IUser.Response.IAccess[]): IRoutes {
  const children = access ? getRouteByAccess(access) : undefined
  const [root, ...reset] = baseRoutes
  return [{ ...root, children }, ...reset]
}

export function findRouteBySearch(
  search: { key: string; type: 'key' | 'path' },
  dict: IRouter.Config.Route[],
  parent?: string
): (IRouter.Config.Route & { parent?: string }) | null {
  let result: (IRouter.Config.Route & { parent?: string }) | null = null
  for (let i = 0; i < dict.length; i++) {
    const current = dict[i]
    if (current[search.type] === search.key) {
      result = { ...current, parent }
      break
    } else if (current.children && Array.isArray(current.children)) {
      result = findRouteBySearch(search, current.children, current.key)
      break
    } else {
      result = null
    }
  }
  return result
}

export default baseRoutes
